﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ChatGPT3._5_Turbo
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }
        public event EventHandler? StartSave;

        public string? IP
        {
            get
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        return txt_IP_Azure.Text;
                    default:
                        return txt_IP_OpenAI.Text;
                }
            }
            set
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        txt_IP_Azure.Text = value;
                        break;
                    default:
                        txt_IP_OpenAI.Text = value;
                        break;
                }
            }
        }

        public string? Port
        {
            get
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        return txt_Port_Azure.Text;
                    default:
                        return txt_Port_OpenAI.Text;
                }
            }
            set
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        txt_Port_Azure.Text = value;
                        break;
                    default:
                        txt_Port_OpenAI.Text = value;
                        break;
                }
            }
        }

        public string? Key
        {
            get
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        return txt_Key_Azure.Text;
                    default:
                        return txt_Key_OpenAI.Text;
                }
                
            }
            set
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        txt_Key_Azure.Text = value;
                        break;
                    default:
                        txt_Key_OpenAI.Text = value;
                        break;
                }
               
            }
        }

        public string? ServerData1
        {
            get
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        return txt_EndPoint_Azure.Text;
                    default:
                        return string.Empty;
                }

            }
            set
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        txt_EndPoint_Azure.Text = value;
                        break;
                    default:
                        break;
                }

            }
        }

        public string? ServerData2
        {
            get
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        return txt_Deploy_Azure.Text;
                    default:
                        return string.Empty;
                }

            }
            set
            {
                switch (tab_ServerType.SelectedIndex)
                {
                    case 1:
                        txt_Deploy_Azure.Text = value;
                        break;
                    default:
                        break;
                }

            }
        }

        public string? UserName
        {
            get
            {
                return txt_UserName.Text;
            }
            set
            {
                txt_UserName.Text = value;
            }
        }

        public string? Password
        {
            get
            {
                return txt_Password.Text;
            }
            set
            {
                if (SavePass)
                    txt_Password.Text = value;
            }
        }

        public bool SavePass
        {
            get
            {
                return chk_SavePass.Checked;
            }
            set
            {
                chk_SavePass.Checked = value;
            }
        }

        public bool IsSSL
        {
            get
            {
                return chk_SSL.Checked;
            }
            set
            {
                chk_SSL.Checked = value;
            }
        }

        /// <summary>
        /// 服务供应商序号
        /// 0：OpenAI直营
        /// 1：Azure OpenAI
        /// </summary>
        public int ServicesIndex { get { return tab_ServerType.SelectedIndex; } set { tab_ServerType.SelectedIndex = value; } }

        /// <summary>
        /// 服务供应商总数
        /// </summary>
        public int ServicesCount { get { return tab_ServerType.TabCount; } }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
 
                #region 检查IP，端口合法性
                if (string.IsNullOrEmpty(IP))
                {
                    string ErrorMsg = "保存前需填写服务器IP";
                    MessageBox.Show(ErrorMsg);
                    return;
                }
                //string[] IPSections = IP.Split('.');
                //if (
                //    IPSections.Length != 4
                //    || !YZZ.工.串.整型吗(IPSections[0])
                //    || !YZZ.工.串.整型吗(IPSections[1])
                //    || !YZZ.工.串.整型吗(IPSections[2])
                //    || !YZZ.工.串.整型吗(IPSections[3])
                //    || YZZ.工.转.ToInt(IPSections[0]) > 255
                //    || YZZ.工.转.ToInt(IPSections[1]) > 255
                //    || YZZ.工.转.ToInt(IPSections[2]) > 255
                //    || YZZ.工.转.ToInt(IPSections[3]) > 255
                //    )
                //{
                //    e.Result = "IP地址不正确";
                //    return;
                //}
                if (string.IsNullOrEmpty(Port))
                {
                    string ErrorMsg = "保存前需填写服务器端口";
                    MessageBox.Show(ErrorMsg);
                    return;
                }
                if (YZZ.工.转.ToInt(Port) > 65535)
                {
                    string ErrorMsg = "端口不正确,端口最大不超过65535";
                    MessageBox.Show(ErrorMsg);
                    return;
                }
                if (string.IsNullOrEmpty(Key))
                {
                    MessageBox.Show("API秘钥不能为空");
                    return;
                }
                #endregion

                BackgroundWorker bg = new BackgroundWorker();
                bg.DoWork += Save_DoWork;
                bg.RunWorkerCompleted += Save_RunWorkerCompleted;
                bg.RunWorkerAsync();
                this.Enabled = false;
            }
            catch (Exception ex)
            { YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                this.Enabled = true;
            }

        }

        private async void Save_RunWorkerCompleted(object? sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                string Result = YZZ.工.转.ToString(e.Result);
                if (string.IsNullOrEmpty(Result))
                {
                    #region 尝试连接，成功则保存
                    string Response = await HandleGetApi("TryConnection");
                    if (!string.IsNullOrEmpty(Response) && Response != "网络连接失败，请确认连接参数是否正确")
                    {

                        #region 保存连接
                        if (StartSave != null)
                            StartSave(this, e);
                        #endregion

                        Result = "保存成功";

                        tabControl1.SelectedTab = tab_Login;
                    }
                    else
                        Result = "保存失败:\r\n" + Response;
                    #endregion
                }


                MessageBox.Show(Result);
  
                //tab_Login.Show();
            }
            catch (Exception ex)
            { YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                MessageBox.Show("保存失败");
            }

            this.Enabled = true;
        }

        private void Save_DoWork(object? sender, DoWorkEventArgs e)
        {
            try
            {


                return;

            }
            catch (Exception ex)
            { 
                YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                
            }
            e.Result = "连接失败，请检查你的服务器IP和端口是否正确";
        }

        public async Task<string> HandleGetApi(string APIName)
        {
            string responseContent = string.Empty;
            try
            {
                if (IsSSL)
                {
                    using (HttpClient _httpClient = new HttpClient())
                    {
                        var apiUrl = "https://" + IP + ":" + Port + "/" + APIName;
                        var response = await _httpClient.GetAsync(apiUrl);
                        responseContent = await response.Content.ReadAsStringAsync();
                    }
                }
                else
                {
                    var httpClientHandler = new HttpClientHandler();
                    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
                    using (HttpClient _httpClient = new HttpClient(httpClientHandler))
                    {
                    
                        var apiUrl = "http://" + IP + ":" + Port + "/" + APIName;
                        //_httpClient.BaseAddress = new Uri(apiUrl);
                        //var response = await _httpClient.GetAsync("endpoint");
                        var response = await _httpClient.GetAsync(apiUrl);
                        responseContent = await response.Content.ReadAsStringAsync();
                    }
                }

              
            }
            catch (Exception ex)
            { YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); responseContent = "网络连接失败，请确认连接参数是否正确"; }
            return responseContent;
        }

        public async Task<string> HandlePostApi(string APIName, string[] parameters)
        {
            string responseContent = string.Empty;
            try
            {
                List<string> data = new List<string>();
                for (int i = 0; i < parameters.Length; i++)
                    data.Add(parameters[i]);
                string json = YZZ.工应.WebAPI.ListToJson(data);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                if (IsSSL)
                {
                    using (HttpClient _httpClient = new HttpClient())
                    {
                        var apiUrl = "https://" + IP + ":" + Port + "/" + APIName;
                        var response = await _httpClient.PostAsync(apiUrl, content);
                        responseContent = await response.Content.ReadAsStringAsync();
                    }
                }
                else
                {
                    var httpClientHandler = new HttpClientHandler();
                    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
                    using (HttpClient _httpClient = new HttpClient(httpClientHandler))
                    {
                        var apiUrl = "http://" + IP + ":" + Port + "/" + APIName;
                        var response = await _httpClient.PostAsync(apiUrl, content);
                        responseContent = await response.Content.ReadAsStringAsync();
                    }
                }

            }
            catch (Exception ex)
            { YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); responseContent = "网络连接失败，请确认连接参数是否正确"; }
            return responseContent;
        }

        private void btn_Login_Click(object sender, EventArgs e)
        {
      
            try
            {
                #region 检查用户名密码合法性
                if (string.IsNullOrEmpty(UserName))
                {
                    MessageBox.Show("请填写用户名");
                    return;
                }

                if (string.IsNullOrEmpty(Password))
                {
                    MessageBox.Show("请填写密码");
                    return;
                }
                #endregion
                BackgroundWorker bg = new BackgroundWorker();
                bg.DoWork += Login_DoWork;
                bg.RunWorkerCompleted += Login_RunWorkerCompleted;
                bg.RunWorkerAsync();
                this.Enabled = false;
            }
            catch (Exception ex)
            {
                YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                this.Enabled = true;
            }
        }

        private async void Login_RunWorkerCompleted(object? sender, RunWorkerCompletedEventArgs e)
        {

            try
            {
                string Result = YZZ.工.转.ToString(e.Result);
                if (string.IsNullOrEmpty(Result))
                {
                    #region 尝试连接，成功则保存
                    string Response = await HandlePostApi("Login", new string[] { UserName, YZZ.工应.WebAPI.getMd5(Password) });
                    if (Response.Contains("成功"))
                    {
                        this.DialogResult = DialogResult.OK;
                        return;
                    }
                    Result = Response;
                    #endregion
                }


                MessageBox.Show(Result);

            }
            catch (Exception ex)
            {
                YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                MessageBox.Show("保存失败");
            }

            this.Enabled = true;


        }

        private void Login_DoWork(object? sender, DoWorkEventArgs e)
        {
            try
            {
                


            }
            catch (Exception ex)
            { YZZ.Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                

            }

        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void btn_Register_Click(object sender, EventArgs e)
        {
            #region 检查服务器是否已填写
            if (string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(Port))
            {
                MessageBox.Show("请先确保服务器信息正确再注册");
            }
            #endregion

            using (RegisterForm rf = new RegisterForm())
            {
                rf.IP = IP;
                rf.Port = Port;
                rf.IsSSL = IsSSL;
                rf.ShowDialog();
                txt_UserName.Focus();
            }
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            tab_Login.Focus();
            gb_UserName.Focus();
            txt_UserName.Focus();
        }
    }
}
